﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SmartAnswerPlatform.Common
{
    public class SqlSugarSteup
    {
        private static SqlSugarClient? client;

        private static SqlSugarClient Instance()
        {
            if (client == null)
            {
                ConnectionConfig connectionConfig = new ConnectionConfig();

                connectionConfig.ConnectionString = "server=.;Database=SmartAnswerPlatform;Uid=sa;Pwd=123456;TrustServerCertificate=True;";
                connectionConfig.DbType = SqlSugar.DbType.SqlServer;
                connectionConfig.IsAutoCloseConnection = true;
                connectionConfig.LanguageType = LanguageType.Chinese;
                connectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
                {
                    //实体和表的对应关系
                    EntityNameService = (type, entity) =>
                    {
                        entity.DbTableName = CamelToUnderline(type.Name);
                    },
                    //属性和列的对应关系
                    EntityService = (property, column) =>
                    {
                        column.DbColumnName = CamelToUnderline(property.Name);

                        /***高版C#写法***/
                        //支持string?和string  
                        if (column.IsPrimarykey == false && new NullabilityInfoContext()
                         .Create(property).WriteState is NullabilityState.Nullable)
                        {
                            column.IsNullable = true;
                        }
                    },
                };

                client = new SqlSugarClient(connectionConfig, db =>
                {
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                        Console.WriteLine(UtilMethods.GetSqlString(SqlSugar.DbType.SqlServer, sql, pars));

                    };
                });
            }
            return client!;
        }
        public static string CamelToUnderline(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            var regex = new Regex("[A-Z]");
            var result = regex.Replace(str, match =>
            {
                if (match.Index == 0)
                {
                    return match.Value.ToLower();
                }
                return '_' + match.Value.ToLower();
            });
            return result;
        }
    }
}
